<template>
    <div class="SongSheet" ref="SongSheet">
        <!-- 导航栏 -->
        <div class="navBar">
            <!-- 返回 -->
            <div class="return" @click="back">
                <van-icon name="arrow-left" />
            </div>

            <!-- 标题 -->
            <div class="tit">{{ tttt }}</div>

            <!-- 更多 -->
            <div class="more" @click="showPopup(true)">
                <img src="../assets/T1-solid-更多.png" alt="" />
            </div>
        </div>

        <!-- 背景图 -->
        <div
            class="bg_box"
            :style="{
                backgroundImage: 'url(' + playlistData.coverImgUrl + ')',
            }"
        ></div>

        <!-- 轮廓 -->
        <div class="describe">
            <!-- 左盒 -->
            <div class="letf">
                <div class="Url_box">
                    <!-- 封面 -->
                    <div class="coverImgUrl">
                        <img :src="playlistData.coverImgUrl" alt="" />
                    </div>
                    <!-- 创造者封面 -->
                    <div class="avatarUrl" @click="showPopup(true)">
                        <img :src="playlistData.avatarUrl" alt="" />
                    </div>
                </div>
            </div>

            <!-- 右盒 -->
            <div class="right">
                <!-- 歌单名 -->
                <div class="name">{{ playlistData.name }}</div>
                <!-- 创建者 -->
                <div class="nickname">{{ playlistData.nickname }}</div>

                <!-- 功能盒 -->
                <div class="fn_box">
                    <!-- 分享 -->
                    <div @click="showShare = true">
                        <img src="../assets/分享小.png" alt="" />分享
                    </div>
                    <!-- 评论 -->
                    <div><img src="../assets/评论小.png" alt="" />评论</div>
                    <!-- 下载 -->
                    <div>
                        <img src="../assets/ic_download.png" alt="" />下载
                    </div>
                </div>
            </div>
        </div>

        <!-- 标题 -->
        <div class="tit2" :class="{ fixed: tit2_fixed }">
            <div class="text">共{{ playlistData.trackIds.length }}首歌</div>
            <div class="goDing" @click="goDing">
                <img src="../assets/回到顶部.png" alt="" />
            </div>
        </div>
        <!-- 单曲盒 -->
        <div class="music_box" ref="music_box" :class="{ fixed: tit2_fixed }">
            <!-- 单曲区 -->
            <div class="music">
                <!-- 单曲元素 -->
                <Single
                    v-for="(item, index) in playlistData.tracks"
                    :key="index"
                    :item="item"
                    :index="index"
                />
            </div>

            <!-- 懒加载开关 -->
            <div class="Lazy" ref="Lazy"></div>
        </div>

        <!-- 分享组件 -->
        <van-share-sheet
            v-model="showShare"
            title="立即分享给好友"
            :options="options"
            @select="onSelect"
        />

        <!-- 弹出层 -->
        <van-popup
            class="popup"
            v-model="show"
            position="top"
            :style="{ height: '30%' }"
            round
        >
            <div class="box">
                <div class="data_box">
                    <div class="p_box">
                        <!-- 歌单创建时间 -->
                        <div class="createTime">歌单创建时间</div>

                        <div class="time1">
                            {{ playlistData.createTime | publishTime_text }}
                        </div>

                        <!-- 歌单最近更新 -->
                        <div class="updateTime">歌单最近更新</div>

                        <div class="time2">
                            {{ playlistData.updateTime | publishTime_text }}
                        </div>
                    </div>

                    <div class="img_box">
                        <img :src="playlistData.avatarUrl" alt="" />
                    </div>

                    <!-- 创建者 -->
                    <div class="avatar">
                        <div class="name">
                            {{ playlistData.nickname }}
                        </div>
                        <div class="but">
                            <van-button
                                color="linear-gradient(to right, #fa9413, #c302fd)"
                                round
                                @click="collectionSonger_Fn"
                            >
                                {{
                                    collectionSonger
                                        ? '取消关注他'
                                        : '关注创建者'
                                }}
                            </van-button>
                        </div>
                    </div>
                </div>
                <!-- 收藏歌单-->
                <div class="collection">
                    <div class="but">
                        <van-button
                            color="linear-gradient(to right, #00ffe8, #f600c1, #fc9514)"
                            round
                            @click="collectionSongList"
                            :disabled="no"
                        >
                            {{ collection ? '取消收藏' : '收藏歌单' }}
                        </van-button>
                    </div>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script>
import { Toast } from 'vant';
import { Dialog } from 'vant';
import { mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers } from 'vuex';
const {
    mapState: controlAudioMapState,
    mapMutations: controlAudioMapMutations,
    mapGetters: controlAudioMapGetters,
    mapActions: controlAudioMapActions
} = createNamespacedHelpers('controlAudio');
const {
    mapState: AccountMapState,
    mapMutations: AccountMapMutations,
    mapGetters: AccountMapGetters,
    mapActions: AccountMapActions
} = createNamespacedHelpers('Account');

import Single from '../components/Single.vue'
export default {
    name: "SongSheet",
    components: { Single },
    filters: {
        // 发布日期 文本
        publishTime_text: (value) => {
            // 获取 时间
            let time = new Date(value);

            let n = time.getFullYear();//年
            let y = time.getMonth() + 1; //月
            let r = time.getDate();//日

            // 补零
            y = y < 10 ? "0" + y : y;
            r = r < 10 ? "0" + r : r;

            // 输出
            return `${n}-${y}-${r}`;
        }
    },
    computed: {
        // 音频的播放状态
        ...controlAudioMapState(['id']),

        ...AccountMapState(['uid']),

        tttt() {
            if (this.$route.query.type == 0) {
                return "我收藏的歌单"
            }
            else if (this.$route.query.type == 1) {
                return "每日推荐歌单"
            }
            else if (this.$route.query.type == 2) {
                return "网友精选歌单"
            }
            else if (this.$route.query.type == 3) {
                return "搜索发现歌单"
            }
        },

        // 歌单收藏状态 f未收藏，t已收藏
        collection() {
            let obj = this.othersIds.find((v, i) => {

                if (v.id == this.playlistData.id) {
                    return true
                } else { return false; }
            });
            console.log('collection ==> obj ', obj);

            if (obj) {
                return true
            } else { return false }
        },


        // 歌手 收藏状态 f未收藏，t已收藏
        collectionSonger() {
            let obj = this.songerIds.find((v, i) => {

                if (v.userId == this.playlistData.userId) {
                    return true
                } else { return false; }
            });
            console.log('collectionSonger ==> 收藏歌手 obj ', obj);

            if (obj) {
                return true
            } else { return false }
        }
    },

    data() {
        return {
            // 会话数据 收藏歌单列表
            othersIds: [],
            // 会话数据 收藏歌手列表
            songerIds: [],
            // 源数据开关
            no: null,


            // 歌单数据
            playlistData: {
                // 歌单id
                id: null,
                // 封面路径
                coverImgUrl: '',
                //   歌单名
                name: '',
                // 创建者
                nickname: '',
                // 创建者 封面
                playlistData: '',
                // 创建者id
                userId: null,

                // 显示单曲
                tracks: [
                    // {
                    //     id: null,
                    //     name: '',
                    //     albumName: ''
                    // }
                ],
                // 后备歌单id
                trackIds: [
                    // {
                    //     id: null
                    // }
                ],
                // 创建时间
                createTime: null,
                // 更新时间
                updateTime: null,
            },

            // SongSheet节点
            domSongSheet: null,
            // Lazy节点
            domLazy: null,
            // tit2节点
            dommusic_box: null,
            tit2_fixed: false,

            // 懒加载定时器
            timer: null,



            // 分享组件 显示开关
            showShare: false,
            // 分享组件 数据
            options: [
                [
                    { name: '微信', icon: 'wechat' },
                    { name: '朋友圈', icon: 'wechat-moments' },
                    { name: '微博', icon: 'weibo' },
                    { name: 'QQ', icon: 'qq' },
                ],
                [
                    { name: '复制链接', icon: 'link' },
                    { name: '分享海报', icon: 'poster' },
                    { name: '二维码', icon: 'qrcode' },
                    { name: '小程序码', icon: 'weapp-qrcode' },
                ],
            ],

            // 弹出层
            show: false,
        }
    },
    methods: {
        ...mapMutations(['VIP_TB_Fn']),
        ...AccountMapMutations(['changeStateProperty']),

        // 返回上一级
        back() { this.$router.back(); },

        // 分享提示
        onSelect(option) { Toast(option.name); },

        // 弹出 弹出层
        showPopup(tf) { this.show = tf; },

        // 回到顶部
        goDing() {
            let num = this.domSongSheet.scrollTop / 40;
            // 无限定时器
            let go = setInterval(() => {
                this.domSongSheet.scrollTop -= num;

                // 到顶了,就销毁
                if (this.domSongSheet.scrollTop <= 0) {
                    this.domSongSheet.scrollTop = 0;
                    clearInterval(go);
                }
            }, 10);
        },

        // 收藏歌单
        collectionSongList() {
            if (!this.uid) { this.$router.push({ name: 'LogOn' }); }
            if (this.collection) {

                Dialog.confirm({
                    title: '确定取消收藏该歌单？',
                })
                    .then(() => {
                        // 删除相同歌单
                        this.othersIds = this.othersIds.filter((v, i) => {
                            if (this.playlistData.id == v.id) {
                                return false
                            } else {
                                return true;
                            }
                        });

                        sessionStorage.setItem(
                            "othersIds",
                            JSON.stringify(this.othersIds)
                        );
                        Toast.success({
                            message: '取消收藏\n成功！',
                            forbidClick: true,
                        });
                    })
                    .catch(() => { });
            }
            else {
                this.othersIds.push({
                    id: this.playlistData.id,
                    coverImgUrl: this.playlistData.coverImgUrl,
                    name: this.playlistData.name,
                    trackCount: this.playlistData.trackIds.length,
                    creatorNickname: this.playlistData.nickname
                });

                sessionStorage.setItem(
                    "othersIds",
                    JSON.stringify(this.othersIds)
                );
                Toast.success({
                    message: '收藏成功！',
                    forbidClick: true,
                });
            };
        },

        // 关注创建者
        collectionSonger_Fn() {
            if (!this.uid) { this.$router.push({ name: 'LogOn' }); }
            if (this.collectionSonger) {
                Dialog.confirm({
                    title: '确定取消关注该创建者？',
                })
                    .then(() => {
                        // 删除创建者id
                        this.songerIds = this.songerIds.filter((v, i) => {
                            if (this.playlistData.userId == v.userId) {
                                return false
                            } else {
                                return true;
                            }
                        });

                        sessionStorage.setItem(
                            "songerIds",
                            JSON.stringify(this.songerIds)
                        );
                        Toast.success({
                            message: '取消关注\n成功！',
                            forbidClick: true,
                        });
                    })
                    .catch(() => { });
            }
            else {
                this.songerIds.push({
                    userId: this.playlistData.userId,
                });

                sessionStorage.setItem(
                    "songerIds",
                    JSON.stringify(this.songerIds)
                );
                Toast.success({
                    message: '关注成功！',
                    forbidClick: true,
                });
            };
        },

        // 滚动监听
        scroll() {
            let music_boxTop = this.dommusic_box.getBoundingClientRect().top;
            // console.log("🚀 ==> scroll ==> music_boxTop ", music_boxTop);
            if (music_boxTop < 57) { this.tit2_fixed = true; }
            else { this.tit2_fixed = false; }


            // 没后备歌单了 停止执行代码块
            if (this.playlistData.tracks.length === this.playlistData.trackIds.length) { return };


            // 获取的是浏览器可见区域高度（网页的可视区域的高度）（不滚动的情况下）
            let documentClientHeight = document.documentElement.clientHeight || window.innerHeight;
            // 指定元素顶端到可见区域（网页）顶端的距离
            let htmlElementClientTop = this.domLazy.getBoundingClientRect().top;


            // 指定元素进入可视区域
            if (documentClientHeight - 70 >= htmlElementClientTop) {
                // console.log(htmlElementClientTop);

                // 判断定时器是否存在 ==> null==false , 存在==true
                if (this.timer) {
                    // 是, 就夹断, 不再往下执行 
                    return
                }

                // [定时器存在, 不往下执行;] [执行完情况序号号后,定时器就不存在了, 就将往下执行代码;]
                // 建立一次性定时器
                this.timer = setTimeout(() => {

                    // 再次确认高度 确定请求加载新数据
                    // 获取的是浏览器可见区域高度（网页的可视区域的高度）（不滚动的情况下）
                    let documentClientHeight = document.documentElement.clientHeight || window.innerHeight;
                    // 指定元素顶端到可见区域（网页）顶端的距离
                    let htmlElementClientTop = this.domLazy.getBoundingClientRect().top;

                    if (documentClientHeight - 70 >= htmlElementClientTop) {
                        this.generate();
                    }

                    //执行结束, 清空定时器序号, 以便进行下次触发执行;
                    this.timer = null;
                }, 1750);
            }
        },

        // 新元素生成
        generate() {
            let tracks_L = this.playlistData.tracks.length;
            console.log("🚀 ==> generate ==> tracks_L", tracks_L);
            let trackIds_L = this.playlistData.trackIds.length;
            console.log("🚀 ==> generate ==> trackIds_L ", trackIds_L);

            // 没后备歌单了 停止执行代码块
            if (tracks_L !== trackIds_L) {
                let ids = '';
                for (let i = 0; i < 30; i++) {
                    if (tracks_L + i === this.playlistData.trackIds.length) {
                        break
                    }
                    ids += this.playlistData.trackIds[tracks_L + i].id + ',';
                }
                ids = ids.slice(0, -1)
                // console.log("🚀 ==> generate ==> ids", ids);


                this.axios({
                    method: "GET",
                    url: "/song/detail",
                    params: { ids }
                }).then((result) => {
                    // console.log("🚀 ==> generate ==> result", result);
                    if (result.data.code === 200) {
                        result.data.songs.forEach((v) => {
                            // 艺术家名字
                            let albumName = "";
                            v.ar.forEach((v) => {
                                albumName += v.name + ' / '
                            })
                            albumName = albumName.slice(0, -3);

                            this.playlistData.tracks.push({
                                id: v.id,
                                name: v.name,
                                albumName
                            });
                        });
                        console.log("新元素生成!");
                        console.log("🚀 ==> generate ==>  this.playlistData.tracks", this.playlistData.tracks);
                    };
                }).catch((err) => {
                    console.log("🚀 ==> generate ==> err", err);
                });
            };
        },

        // 请求歌单数据
        getPlayListDetail(id) {
            this.axios({
                method: "GET",
                url: "/playlist/detail",
                params: { id }
            }).then((result) => {
                console.log("🚀 ==> getPlayListDetail ==> result", result);
                if (result.data.code === 200) {
                    this.playlistData.coverImgUrl = result.data.playlist.coverImgUrl + '?param=140y140';
                    this.playlistData.createTime = result.data.playlist.createTime;
                    this.playlistData.updateTime = result.data.playlist.updateTime;
                    this.playlistData.name = result.data.playlist.name;
                    this.playlistData.nickname = result.data.playlist.creator.nickname;
                    this.playlistData.avatarUrl = result.data.playlist.creator.avatarUrl + '?param=140y140';
                    this.playlistData.userId = result.data.playlist.creator.userId;

                    // 后备歌单id
                    result.data.playlist.trackIds.forEach((v) => {
                        this.playlistData.trackIds.push({ id: v.id });
                    });

                    // 显示单曲
                    result.data.playlist.tracks.forEach((v) => {

                        // 艺术家名字
                        let albumName = "";
                        v.ar.forEach((v) => {
                            albumName += v.name + ' / '
                        })
                        albumName = albumName.slice(0, -3);

                        this.playlistData.tracks.push({
                            id: v.id,
                            name: v.name,
                            albumName
                        });
                    });


                    console.log("🚀 ==> getPlayListDetail ==> this.playlistData", this.playlistData);
                }
            }).catch((err) => {
                console.log("🚀 ==> getPlayListDetail ==> err", err);
            });
        },
    },

    // 初始化
    created() {
        this.VIP_TB_Fn(true);

        console.log("歌单id ===> ", this.$route.query.id);
        this.playlistData.id = this.$route.query.id;
        this.no = Boolean(this.$route.query.no);

        // 获取会话中的 收藏歌单列表
        this.othersIds = sessionStorage.getItem("othersIds");
        if (this.othersIds) {
            this.othersIds = JSON.parse(this.othersIds);
        } else {
            this.othersIds = [];
        }

        // 获取会话中的 收藏歌手列表
        this.songerIds = sessionStorage.getItem("songerIds");
        if (this.songerIds) {
            this.songerIds = JSON.parse(this.songerIds);
        } else {
            this.songerIds = [];
        }



        // 请求歌单数据
        this.getPlayListDetail(this.$route.query.id);
        this.$nextTick(() => {
            let vuethis = this;

            // 获取歌手节点 
            this.domSongSheet = this.$refs.SongSheet;
            // console.log("🚀 ==> this.$nextTick ==>   this.domSongSheet ", this.domSongSheet);

            // 监听 歌手节点页面 滚动事件
            this.domSongSheet.onscroll = function () { vuethis.scroll(); };

            // 获取懒加载开关
            this.domLazy = this.$refs.Lazy;
            // console.log("🚀 ==> this.$nextTick ==> this.domLazy", this.domLazy);

            // 获取 标题2 节点
            this.dommusic_box = this.$refs.music_box;
            // console.log("🚀 ==> this.$nextTick ==> this.dommusic_box", this.dommusic_box);
        });


    },
}
</script>

<style lang="less" scoped>
.SongSheet {
    position: fixed;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    padding-bottom: 80px;
    background-color: #131226;
    overflow: scroll;

    // 导航栏
    .navBar {
        z-index: 2;
        display: flex;
        justify-content: space-between;
        align-items: center;
        position: absolute;
        top: 10px;
        right: 0;
        left: 0;
        padding: 15px;

        // 返回
        .return {
            font-size: 26px;
            color: #9893cd;
            margin: 0 5px;
        }
        // 标题
        .tit {
            color: #fff;
            font-size: 18px;
        }

        // 更多
        .more {
            width: 36px;
        }
    }

    // 背景图
    .bg_box {
        height: 30%;
        background-size: 500px;
        background-position: center center;
        overflow: hidden;
        position: relative;

        &::after {
            content: '';
            position: absolute;
            left: -5px;
            right: -5px;
            bottom: -4px;
            height: 10px;
            filter: blur(5px);
            background-image: linear-gradient(90deg, #0108d2, #b601e1);
        }
    }

    //轮廓
    .describe {
        margin: 0 20px -42px;
        transform: translateY(-70px);
        display: flex;

        // 左盒
        .letf {
            flex-shrink: 0;
            width: 120px;
            height: 120px;
            position: relative;
            overflow: hidden;
            border-radius: 5px;
            box-shadow: 0px 2px 2px 2px rgba(1, 3, 217, 0.9);

            .Url_box {
                display: flex;
                width: 340px;
                height: 170px;
                position: absolute;
                top: -25px;
                left: -110px;
                // opacity: 0.4;
                transform: rotate(-45deg);
                overflow: hidden;
                // 封面
                .coverImgUrl {
                    width: 50%;
                    height: 100%;
                    overflow: hidden;
                    img {
                        width: 120px;
                        height: 120px;
                        display: block;
                        transform: rotate(45deg) translateY(-60px)
                            translateX(95px);
                        z-index: -1;
                    }
                }
                // 创造者封面
                .avatarUrl {
                    overflow: hidden;
                    width: 50%;
                    height: 100%;

                    img {
                        z-index: -1;
                        width: 120px;
                        height: 120px;
                        display: block;
                        transform: rotate(45deg) translateY(60px)
                            translateX(-24px);
                    }
                }
            }
        }

        // 右盒
        .right {
            margin-left: 20px;
            width: 195px;
            position: relative;
            display: flex;
            flex-flow: column;
            align-items: flex-start;

            // 歌单名
            .name {
                color: #fff;
                font-size: 15px;
                max-width: 195px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                word-break: break-all;
                line-height: 20px;
                margin-bottom: 10px;
                padding: 3px 6px 5px;
                border-radius: 5px;
                background-color: rgba(0, 0, 0, 0.3);
            }

            // 创造者昵称
            .nickname {
                max-width: 195px;
                color: rgba(255, 255, 255, 0.603);
                font-size: 12px;
                padding: 3px 6px 5px;
                border-radius: 5px;
                background-color: rgba(0, 0, 0, 0.3);

                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                word-break: break-all;
            }

            // 功能盒
            .fn_box {
                position: absolute;
                bottom: 0;
                display: flex;
                color: #fff;
                right: 0;
                left: 0;
                justify-content: space-between;
                padding-right: 15px;

                div {
                    opacity: 0.9;
                    align-items: center;
                    display: flex;
                    flex-flow: column;
                    font-size: 12px;

                    img {
                        width: 26px;
                        height: 26px;
                        margin-bottom: 5px;
                    }
                }
            }
        }
    }

    // 标题
    .tit2 {
        padding: 20px 0;
        display: flex;
        justify-content: space-between;

        &.fixed {
            position: fixed;
            top: 0;
            right: 0;
            left: 0;
            z-index: 5;
            background-color: #131226;
            padding: 15px 0;
            align-items: center;

            .goDing {
                display: flex;
                margin-right: 22px;
                width: 27px;
                height: 27px;
                opacity: 0.8;
            }
        }

        .text {
            display: inline-block;
            margin-left: 20px;
            font-weight: 600;
            font-size: 17px;
            letter-spacing: 2px;
            background-image: linear-gradient(90deg, #e652d8, #2b97fc);
            background-clip: text;
            -webkit-background-clip: text;
            color: transparent;
        }

        .goDing {
            display: none;
        }
    }

    // 单曲盒
    .music_box {
        &.fixed {
            margin-top: 57px;
        }
    }

    /deep/ .van-share-sheet__options {
        padding-right: 8px;
        justify-content: space-around;
    }
}

.van-popup.popup {
    background-color: #2c2c2c;

    .box {
        height: 100%;
        padding: 10px 15px 15px;
        display: flex;
        flex-flow: column;
        justify-content: space-between;

        .data_box {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .p_box {
                flex-shrink: 0;
                .createTime {
                    font-size: 14px;
                    margin-bottom: 5px;
                    color: #727173;
                    font-weight: 600;
                    letter-spacing: 1px;
                }
                .time1 {
                    margin-bottom: 18px;
                    color: #fff;
                }

                .updateTime {
                    font-size: 14px;
                    letter-spacing: 1px;
                    color: #727173;
                    font-weight: 600;
                    margin-bottom: 5px;
                }

                .time2 {
                    color: #fff;
                }
            }
            .img_box {
                flex-shrink: 0;
                margin-left: 15px;
                img {
                    width: 100px;
                    border-radius: 50%;
                }
            }

            .avatar {
                display: flex;
                flex-flow: column;
                align-items: center;
                justify-content: center;

                .name {
                    max-width: 90px;
                    font-size: 15px;
                    margin-bottom: 15px;
                    margin-top: 10px;
                    color: #fff;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    word-break: break-all;
                }

                .but {
                    button {
                        height: 30px;

                        .van-button__text {
                            font-size: 12px;
                        }
                    }
                }
            }
        }

        .collection {
            padding: 0 15px;
            .but {
                button {
                    width: 100%;
                    letter-spacing: 7px;
                }
            }
        }
    }
}
</style>